﻿using MediatR;
using Microsoft.Extensions.Logging;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Organizations;
using Sgr.UPMS.Domain.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Organizations
{
    public class RecoverOrgCommandHandler : IRequestHandler<RecoverOrgCommand, CommandResult<bool>>
    {
        private readonly IOrganizationRepository _organizationRepository;
        private readonly ICurrentUser _currentUser;
        private readonly IUserRepository _userRepository;
        private static readonly string[] propertiesToInclude = new string[] { "Roles" };

        public RecoverOrgCommandHandler(
            IOrganizationRepository organizationRepository,
            IUserRepository userRepository,
            ICurrentUser currentUser)
        {
            _organizationRepository = organizationRepository;
            _userRepository = userRepository;
            _currentUser = currentUser;
        }

        public async Task<CommandResult<bool>> Handle(RecoverOrgCommand request, CancellationToken cancellationToken)
        {
            // 检查当前用户是否有权限恢复组织机构
            // 仅运维人员可以恢复组织机构

            var org = await _organizationRepository.GetAsync(request.Id, cancellationToken);
            if (org == null)
                return CommandResult.NotFound<bool>("未找到指定的组织机构");

            // 组织注销前审查
            var userValidationResult = ValidateRules(cancellationToken);
            if (!userValidationResult)
                return CommandResult.Unauthorized<bool>($"您没有权限恢复组织机构 [{org.Name}]");

            if (!org.TryRecover())
                return CommandResult.Invalid<bool>("组织机构不在恢复期内或恢复失败");

            // 更新状态
            await _organizationRepository.UpdateAsync(org, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "组织恢复成功");
        }

        /// <summary>
        /// 验证用户是否有权限恢复组织
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>验证结果，true表示验证通过，false表示验证失败</returns>
        private bool ValidateRules(CancellationToken cancellationToken)
        {
            // 仅 Constant.SUPER_ADMIN_ORG_ID 组织下的用户方可执行注销操作
            if (!long.TryParse(_currentUser.OrgId, out long orgId))
                return false;

            return orgId == Constant.SUPER_ADMIN_ORG_ID;
        }
    }
}